import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import AutoImport from "unplugin-auto-import/vite";
import yaml from "@rollup/plugin-yaml";
import UnoCSS from "unocss/vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import VueI18nPlugin from "@intlify/unplugin-vue-i18n/vite";
import PurgeIcons from "vite-plugin-purge-icons";

// 路径解析工具
const resolvePath = (dir) => path.resolve(__dirname, dir);

// 获取环境变量
const { VITE_APP_PORT, VITE_APP_BASE_URL, VITE_APP_PROXY_PREFIX } = process.env;

// 配置代理前缀，如果环境变量未定义，则使用默认值
const proxyPrefix = "/api";
export default defineConfig({
  base: "/",
  plugins: [
    vue(),
    yaml({ transform: "json", exclude: "node_modules/**" }),
    AutoImport({
      resolvers: [ElementPlusResolver()], // 自动导入 ElementPlus 组件
    }),
    Components({
      resolvers: [ElementPlusResolver()], // 组件自动按需引入
    }),
    UnoCSS(),
    VueI18nPlugin({
      runtimeOnly: true,
      compositionOnly: true,
      include: [resolvePath("src/locales/**")],
    }),
    createSvgIconsPlugin({
      iconDirs: [resolvePath("src/assets/svgs")],
      symbolId: "icon-[dir]-[name]",
      svgoOptions: true,
    }),
    PurgeIcons(),
  ],
  css: {
    preprocessorOptions: {
      less: {
        additionalData: '@import "./src/assets/theme/variables.module.less";',
        javascriptEnabled: true,
      },
    },
  },
  optimizeDeps: {
    include: [
      "vue",
      "vue-router",
      "vue-types",
      "element-plus/es/locale/lang/zh-cn",
      "element-plus/es/locale/lang/en",
      "@iconify/iconify",
      "@vueuse/core",
      "axios",
      "qs",
      "echarts",
      "echarts-wordcloud",
      "qrcode",
      "@wangeditor/editor",
      "@wangeditor/editor-for-vue",
      "vue-json-pretty",
      "@zxcvbn-ts/core",
      "dayjs",
      "cropperjs",
    ],
  },
  resolve: {
    alias: {
      "@": resolvePath("src"), // `@` 映射到 `src`
      "@cps": resolvePath("src/components"), // `@cps` 映射到 `src/components`
      "@assets": resolvePath("src/assets"), // `@assets` 映射到 `src/assets`
      "@cwd": resolvePath("src/components/wd-components"),
    },
    extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"], // 自动解析文件扩展名
  },
  server: {
    // historyApiFallback: true,
    host: true, // 设置服务器主机为 0.0.0.0 以便在网络上访问
    port: VITE_APP_PORT || process.env.PORT || 4080, // 设置服务器端口
    // strictPort: true, // 若端口被占用则直接退出
    // fs: {
    //   strict: true, // 严格限制访问文件系统的权限
    // },
    proxy: {
      '/api': {
        target: "http://agentapi.wyyp.com.cn", // 代理目标 URL
        changeOrigin: true, // 更改源，避免跨域问题
        rewrite: (path) => path.replace(/^\/api/, ""), // 重写路径
      },

    },
  },
});
